package com.sas.web.panel.articles;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.wicket.Page;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.OrderByBorder;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.sas.domain.Article;
import com.sas.model.EntityModel;
import com.sas.repository.ArticleRepository;
import com.sas.web.articles.ArticleSinglePage;
import com.sas.web.articles.SellingPage;


@SuppressWarnings("serial")
public class ArticlesListPanel extends Panel {
	private Article selectedArticle;
	private ModalWindow modal1 = null;
	private ArticleFieldTreePanel aftp;
	
	@SpringBean
	private ArticleRepository articleRepo;
	
	public ArticlesListPanel(String id, final ArticleFieldTreePanel aftp) {
		super(id);
		this.aftp = aftp;		
		SortableDataProvider<IModel<Article>> dp = new ArticleSortableDataProvider();
		dp.setSort("name", true);
		
		final DataView<IModel<Article>> dataView = createDataView2(dp);
		
		add(new OrderByBorder("orderByCode", "code", dp) {
            @Override
            protected void onSortChanged()
            {
                dataView.setCurrentPage(0);
            }
        });

        add(new OrderByBorder("orderByName", "name", dp) {
            @Override
            protected void onSortChanged()
            {
                dataView.setCurrentPage(0);
            }
        });
       
     	 
        add(modal1 = new ModalWindow("modal"));
        
        
        add(dataView);
        add(new PagingNavigator("navigator", dataView));
		
	}

	private DataView<IModel<Article>> createDataView2(
			SortableDataProvider<IModel<Article>> dp) {
		
		DataView<IModel<Article>> ret = new DataView<IModel<Article>>("articlesList", dp) {
			@Override
			protected void populateItem(final Item<IModel<Article>> item) {
				item.add(new Link<Void>("select") {
	                @Override
	                public void onClick() {
	                    setSelectedArticle(((IModel<Article>)item.getDefaultModelObject()).getObject());
	                }
	            });
				
				IModel<Article> imodel = item.getModelObject();
				Article a = imodel.getObject();
				
				item.add(new Label("code", a.getCode()));
				item.add(new Label("name", a.getName()));
				item.add(new Label("description", a.getDescription()));
				item.add(new Label("priceSell", a.getPriceSell() == null ? "0.0" : a.getPriceSell().toString()));
				
				item.add(new AjaxLink<Void>("show") {

					@Override
					public void onClick(AjaxRequestTarget target) {
						modal1.setPageMapName("modal-1");
						modal1.setCookieName("modal-1");
						
						modal1.setPageCreator(new ModalWindow.PageCreator() {
							public Page createPage()
							{
								return new ArticleSinglePage((IModel<Article>) getParent().getDefaultModelObject(), modal1);
							}
						});
						
						modal1.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
							@Override
							public void onClose(AjaxRequestTarget target) {
								setResponsePage(getPage());								
							}
						});
						
						modal1.show(target);
					}
	            });
				
				item.add(new AjaxLink<Void>("sell") {

					@Override
					public void onClick(AjaxRequestTarget target) {
						modal1.setPageMapName("modal-1");
						modal1.setCookieName("modal-1");
						
						modal1.setPageCreator(new ModalWindow.PageCreator() {
							public Page createPage()
							{
								return new SellingPage((IModel<Article>) getParent().getDefaultModelObject(), modal1);
							}
						});
						
						modal1.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
							@Override
							public void onClose(AjaxRequestTarget target) {
								setResponsePage(getPage());								
							}
						});
						
						modal1.show(target);
					}
	            });
				
//				item.add(new AjaxLink<Void>("buy") {
//
//					@Override
//					public void onClick(AjaxRequestTarget target) {
//						modal1.setPageMapName("modal-1");
//						modal1.setCookieName("modal-1");
//						
//						modal1.setPageCreator(new ModalWindow.PageCreator() {
//							public Page createPage()
//							{
//								return new BuyingPage((IModel<Article>) getParent().getDefaultModelObject(), modal1);
//							}
//						});
//						
//						modal1.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {
//							@Override
//							public void onClose(AjaxRequestTarget target) {
//								setResponsePage(getPage());								
//							}
//						});
//						
//						modal1.show(target);
//					}
//	            });
			}
		};
		
		return ret;
		
	}

	public ArticlesListPanel(String id, String articleCode, final List<IModel<Article>> searchList) {
		super(id);
		SortableDataProvider<IModel<Article>> dp = new SortableDataProvider<IModel<Article>>() {
			@Override
			public Iterator<IModel<Article>> iterator(int first, int count) {
				return searchList.iterator();
			}

			@Override
			public IModel<IModel<Article>> model(final IModel<Article> object) {
				return new LoadableDetachableModel<IModel<Article>>() {

					@Override
					protected IModel<Article> load() {
						return object;
					}
				}; 
			}

			@Override
			public int size() {
				return searchList == null ? 0 : searchList.size();
			}
		};
		dp.setSort("name", true);
		
		final DataView<IModel<Article>> dataView = createDataView2(dp); 
		
		add(new OrderByBorder("orderByCode", "code", dp) {
            @Override
            protected void onSortChanged() {
                dataView.setCurrentPage(0);
            }
        });

        add(new OrderByBorder("orderByName", "name", dp) {
            @Override
            protected void onSortChanged() {
                dataView.setCurrentPage(0);
            }
        });
        
        add(modal1 = new ModalWindow("modal"));

        add(dataView);
        add(new PagingNavigator("navigator", dataView));
		
	}

	public ArticlesListPanel(String id) {
		this(id, null, null);
	}


	public void setSelectedArticle(Article selectedArticle) {
		this.selectedArticle = selectedArticle;
	}

	public Article getSelectedArticle() {
		return selectedArticle;
	}
	
	private class ArticleSortableDataProvider extends SortableDataProvider<IModel<Article>> {
		@Override
		public Iterator<? extends IModel<Article>> iterator(int first,
				int count) {
			SortParam sortParam = getSort();
			List<Article> list = articleRepo.findByArticleField(aftp.getSelectedArticleField().getObject(), sortParam.getProperty(), sortParam.isAscending());
			List<IModel<Article>> listIModel = new ArrayList<IModel<Article>>();
			for (Article a: list) {
				listIModel.add(new EntityModel<Article>(Article.class, a));
			}
			return listIModel.iterator();
		}

		@Override
		public IModel<IModel<Article>> model(final IModel<Article> object) {
			return new LoadableDetachableModel<IModel<Article>>() {
				@Override
				protected IModel<Article> load() {
					return object;
				}
			};
		}

		@Override
		public int size() {
			List<Article> list = articleRepo.findByArticleField(aftp.getSelectedArticleField().getObject(), getSort().getProperty(), true);
			return list.size();
		}
		
	}

}
